package com.fwtai.service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * 使用阿里巴巴创建线程池构建异步处理,推荐
 * @作者 田应平
 * @版本 v1.0
 * @创建时间 2022-07-18 21:51
 * @QQ号码 444141300
 * @Email service@dwlai.com
 * @官网 http://www.fwtai.com
*/
public final class AsyncHandler<T>{

  /**
   * 用法:return new AsyncHandler<String>().asyncCompute(()->{return "返回类型为字符串,因为new 的尖括号里的类型是String";}).join();
  */
  public CompletableFuture<T> asyncCompute(final Supplier<T> supplier){
    //todo 使用阿里巴巴推荐的创建线程池的方式,防止OOM
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(
      Runtime.getRuntime().availableProcessors()*32,76800,1L,TimeUnit.SECONDS,new LinkedBlockingQueue<>(51200),new ThreadPoolExecutor.CallerRunsPolicy()
    );
    try {
      return CompletableFuture.supplyAsync(supplier,executor);
    }finally{
      executor.shutdown();//释放线程池
    }
  }

  /**用法:new AsyncHandler<>().asyncConsumer(()->{});*/
  public void asyncConsumer(final Runnable command){
    //todo 使用阿里巴巴推荐的创建线程池的方式,防止OOM
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(
      Runtime.getRuntime().availableProcessors()*32,76800,1L,TimeUnit.SECONDS,new LinkedBlockingQueue<>(51200),new ThreadPoolExecutor.CallerRunsPolicy()
    );
    try {
      executor.execute(command);
    }finally{
      executor.shutdown();
    }
  }
}